<template>
  <div class="page">
    <div class="search">
      <a-form-model :form="form" :label-col="labelCol" :wrapper-col="wrapperCol" @submit.pre.prevent="search">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="活动名称" prop="mcName">
              <a-input v-model="form.mcName" placeholder="请输入活动名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="活动编号" prop="mcNo">
              <a-input v-model="form.mcNo" placeholder="请输入活动编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="活动类型" prop="mcType">
              <a-select v-model="form.mcType" placeholder="请选择活动类型">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="00">满额立减固定金额</a-select-option>
                <a-select-option value="01">满额立减随机金额</a-select-option>
                <a-select-option value="02">满额固定折扣</a-select-option>
                <a-select-option value="03">满额随机折扣</a-select-option>
                <a-select-option value="10">卡券类-免费类-代金券</a-select-option>
                <a-select-option value="11">卡券类-购买类-代金券</a-select-option>
                <a-select-option value="20">手续费减免优惠活动</a-select-option>
                <a-select-option value="30">代理商分润活动</a-select-option>
                <a-select-option value="40">收银员返现活动</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="创建时间" prop="mchntName">
              <a-range-picker v-model="form.rangeTime"></a-range-picker>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="text-align: center;">
            <a-space>
              <a-button type="primary" html-type="submit">查询</a-button>
              <a-button @click="reset">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <a-table :data-source="dataSource" :columns="columns" :pagination="pagination" :scroll="{x: true}" row-key="mcNo"
             class="scrollable" @change="pageChange">
      <template v-slot:operation="text, record">
        <a-space style="white-space: nowrap">
          <a-icon type="eye" theme="twoTone" twoToneColor="#4a9ff5" @click="view(record)" title="详情"
                  v-has-permission="['marketCheck:view']"></a-icon>
          <a-icon type="check-circle" theme="twoTone" twoToneColor="#4a9ff5" @click="check(record)" title="审核"
                  v-has-permission="['marketCheck:check']"></a-icon>
        </a-space>
      </template>
    </a-table>
    <component :is="component" ref="detail" @refresh="fetch"></component>
    <commission-market-manager-operation ref="CommissionMarketManagerOperation"
                                         @refresh="fetch"></commission-market-manager-operation>
  </div>
</template>

<script>
import moment from 'moment'
import CashierManagerOperation from '@/views/bizimpl/upmp/market/cashierManager/CashierManagerOperation'
import CommissionMarketManagerOperation
  from '@/views/bizimpl/upmp/commissionMarketManager/CommissionMarketManagerOperation'
import MarketActiManageForCustOperation
  from '@/views/bizimpl/upmp/market/marketActiManageForCust/MarketActiManageForCustOperation';

export default {
  name: 'Check',
  data() {
    return {
      component: null,
      form: {
        mcName: '',
        mcNo: '',
        mcType: '',
        rangeTime: []
      },
      labelCol: {span: 8},
      wrapperCol: {span: 16},
      dataSource: [],
      columns: [
        {title: "优惠活动名称", dataIndex: "mcName"},
        {title: "优惠活动编号", dataIndex: "mcNo"},
        {
          title: "活动类型",
          dataIndex: "mcType",
          customRender(text) {
            return ({
              "00": "满额立减固定金额",
              "01": "满额立减随机金额",
              "02": "满额固定折扣",
              "03": "满额随机折扣",
              "10": "卡券类-免费类-代金券",
              "11": "卡券类-购买类-代金券",
              "20": "手续费减免优惠活动",
              "30": "代理商分润活动",
              "40": "收银员返现活动"
            })[text] || ''
          }
        },
        {
          title: "活动起始日期",
          dataIndex: "mcStartDate",
          customRender(text) {
            return moment(text).format('YYYY-MM-DD')
          }
        },
        {
          title: "活动终止日期",
          dataIndex: "mcEndDate",
          customRender(text) {
            return moment(text).format('YYYY-MM-DD')
          }
        },
        {
          title: "活动状态",
          dataIndex: "mcStatus",
          customRender(text) {
            return ({
              "0": "草稿",
              "1": "未发布",
              "2": "进行中",
              "3": "已暂停",
              "4": "自然结束",
              "5": "强制结束",
              "6": "测试中",
              "9": "已结束",
            })[text] || ''
          }
        },
        {
          title: "活动审核状态",
          dataIndex: "auditStatus",
          customRender(text) {
            return ({
              "00": "待提交审批",
              "01": "新增-审批流程中",
              "02": "新增-审批通过",
              "03": "新增-审批拒绝",
              "11": "注销-审批流程中",
              "12": "注销-审批通过",
              "13": "注销-审批拒绝",
              "21": "停用-审批流程中",
              "22": "停用-审批通过",
              "23": "停用-审批拒绝",
              "31": "启用-审批流程中",
              "32": "启用-审批通过",
              "33": "启用-审批拒绝",
              "41": "修改-审批流程中",
              "42": "修改-审批通过",
              "43": "修改-审批拒绝",
              "51": "发布-审批流程中",
              "52": "发布-审批通过",
              "53": "发布-审批拒绝",
            })[text] || ''
          }
        },
        {title: "活动预算", dataIndex: "budget"},
        {title: "已消耗预算", dataIndex: "budgetUsed"},
        {
          title: "创建时间",
          dataIndex: "createTime",
          customRender(text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: {customRender: 'operation'}
        }
      ],
      pagination: {
        pageSizeOptions: ['5', '10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
    }
  },
  methods: {
    pageChange(e) {
      this.pagination.current = e.current;
      this.pagination.pageSize = e.pageSize;
      this.fetch();
    },
    async fetch() {
      let params = {
        mcName: this.form.mcName || null,
        mcNo: this.form.mcNo || null,
        mcType: this.form.mcType || null,
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize
      };
      if (this.form.rangeTime && this.form.rangeTime.length === 2) {
        params.startTime = this.form.rangeTime[0].format('YYYY-MM-DD') + " 00:00";
        params.endTime = this.form.rangeTime[1].format('YYYY-MM-DD') + " 23:59";
      }
      const hideLoading = this.$message.loading("加载中...", 0);
      try {
        const res = await this.$get('/admin/market/check/list', params);
        this.dataSource = res.data.records || [];
        this.$set(this.pagination, "total", +res.data.total);
      } catch (e) {
        this.$message.error('网络错误，请稍后再试！')
        console.error(e)
      }
      hideLoading()
    },
    search() {
      this.pagination = Object.assign({}, {
        current: 1,
        pageSize: 10
      })
      this.fetch();
    },
    async reset() {
      this.form = {
        mcName: '',
        mcNo: '',
        mcType: '',
        rangeTime: []
      }
      this.search()
    },
    resolveBeanInfo(data) {
      const detailData = JSON.parse(data.datailData)
      const mcInfoObj = detailData.mcInfoObj;
      const orgInfoList = detailData.orgInfoList;
      const mchntInfoList = detailData.mchntInfoList;
      const productInfoList = detailData.productInfoList;
      const ruleInfoList = detailData.ruleInfoList;
      return {
        mcNo: data.mcNo, // 营销活动编号
        mcName: mcInfoObj.mcName, // 营销活动名称
        orgInfo: orgInfoList.map(i => i.orgId), // 参与机构
        mcDateRange: [moment(mcInfoObj.mcStartDate), moment(mcInfoObj.mcEndDate)], // 活动起始时间
        discountTransferMode: mcInfoObj.discountTransferMode, // 活动优惠方式
        budget: +mcInfoObj.budget, // 返现金额  数字格式 隐式转换
        merchantInfo: mchntInfoList.filter(i => i.mchntType === '0'), // 商户信息
        merchantCircleInfo: mchntInfoList.filter(i => i.mchntType === '1'), // 商圈信息
        upLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易
        criteriaLimit: +mcInfoObj.criteriaLimit, // 有效交易定义
        statPeriod: mcInfoObj.statPeriod, // 统计周期
        criteriaAmount: +mcInfoObj.criteriaAmount, // 周期内收银员交易金额达标
        criteriaFlag: mcInfoObj.criteriaFlag, // 周期内收银员交易金额达标条件计算方式
        criteriaQuantity: +mcInfoObj.criteriaQuantity, // 周期内收银员交易笔数达标
        cashbackMethod: mcInfoObj.cashbackMethod, // 营销方式交易类型
        ruleInfo: ruleInfoList, // 营销方式阶梯规则
        quantityLimitPerson: mcInfoObj.quantityLimitPerson, // 单个收银员统计交易笔数上限
        amountLimitPerson: mcInfoObj.amountLimitPerson, // 单个收银员统计交易金额上限
        cashbackLimitPerson: mcInfoObj.cashbackLimitPerson, // 单个收银员返现金额上限
        quantityLimitMc: mcInfoObj.quantityLimitMc, // 纳入返现总交易笔数上限
        amountLimitMc: mcInfoObj.amountLimitMc, // 纳入返现总交易金额上限
        cashbackLimitMc: mcInfoObj.cashbackLimitMc, // 返现总金额上限
        publishRefuseReason: mcInfoObj.publishRefuseReason, // 发布意见
        auditRefuseReason: mcInfoObj.auditRefuseReason, // 审核意见
        payAcctNo: mcInfoObj.payAcctNo, // 支付账号
      }
    },
    resolveBeanInfo2(data) {
      //详细页面标识
      const detailData = JSON.parse(data.datailData)
      const mcInfoObj = detailData.mcInfoObj;
      const orgInfoList = detailData.orgInfoList;
      const mchntInfoList = detailData.mchntInfoList;
      const productInfoList = detailData.productInfoList;
      const ruleInfoList = detailData.ruleInfoList;
      //优惠劵
      const flag = data.flag
      let beforeFlagView = false;
      let stockMchnt = true;
      let afterFlagView = '0';
      let newMchntFlagView = false;
      let postponeFlagView = false;
      let quantityLimit = null;
      let amountLimit = null;
      let feeLimit = null;
      //达标前手续费优惠规则
      if (mcInfoObj.beforeFlag === '1') {
        beforeFlagView = true
      }
      //存量商户达标条件
      if (mcInfoObj.stockMchntFlag === '0') {
        stockMchnt = false
      }
      //达标后手续费优惠规则
      if (mcInfoObj.afterFlag > 0) {
        afterFlagView = '1'
      }
      //新增商户支持标志
      if (mcInfoObj.newMchntFlag > 0) {
        newMchntFlagView = true
      }
      ///新增商户周期顺延标志
      if (mcInfoObj.postponeFlag > 0) {
        postponeFlagView = true
      }
      //单个存量商户优惠交易笔数上限
      if (mcInfoObj.quantityLimit !== '0.00') {
        quantityLimit = mcInfoObj.quantityLimit
      }
      //单个存量商户优惠交易金额上限
      if (mcInfoObj.amountLimit !== '0.00') {
        amountLimit = mcInfoObj.amountLimit
      }
      //单个存量商户手续费优惠额上限
      if (mcInfoObj.feeLimit !== '0.00') {
        feeLimit = mcInfoObj.feeLimit
      }
      return {
        mcNo: data.mcNo, // 营销活动编号
        mcName: mcInfoObj.mcName, // 营销活动名称
        orgInfo: orgInfoList.map(i => i.orgId), // 参与机构
        mcDateRange: [moment(mcInfoObj.mcStartDate), moment(mcInfoObj.mcEndDate)], // 活动起始时间
        discountTransferMode: mcInfoObj.discountTransferMode, // 活动优惠方式
        budget: +mcInfoObj.budget, // 返现金额  数字格式 隐式转换
        merchantInfo: mchntInfoList.filter(i => i.mchntType === '0'), // 商户信息
        merchantCircleInfo: mchntInfoList.filter(i => i.mchntType === '1'), // 商圈信息
        upLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易
        onLineProduce: productInfoList.map(i => i.bizProdCode), // 纳入营销的交易 线下
        criteriaLimit: +mcInfoObj.criteriaLimit, // 有效交易定义
        statPeriod: mcInfoObj.statPeriod, // 统计周期
        criteriaAmount: +mcInfoObj.criteriaAmount, // 周期内收银员交易金额达标
        criteriaFlag: mcInfoObj.criteriaFlag, // 周期内收银员交易金额达标条件计算方式
        criteriaQuantity: +mcInfoObj.criteriaQuantity, // 周期内收银员交易笔数达标
        cashbackMethod: mcInfoObj.stockMchntType, // 营销方式交易类型
        ruleInfo: ruleInfoList, // 营销方式阶梯规则
        quantityLimitPerson: mcInfoObj.quantityLimitPerson, // 单个收银员统计交易笔数上限
        amountLimitPerson: mcInfoObj.amountLimitPerson, // 单个收银员统计交易金额上限
        cashbackLimitPerson: mcInfoObj.cashbackLimitPerson, // 单个收银员返现金额上限
        quantityLimitMc: mcInfoObj.quantityLimitMc, // 纳入返现总交易笔数上限
        amountLimitMc: mcInfoObj.amountLimitMc, // 纳入返现总交易金额上限
        cashbackLimitMc: mcInfoObj.cashbackLimitMc, // 返现总金额上限
        publishRefuseReason: mcInfoObj.publishRefuseReason, // 发布意见
        auditRefuseReason: mcInfoObj.auditRefuseReason, // 审核意见
        payAcctNo: mcInfoObj.payAcctNo, // 支付账号
        //优惠劵
        newMchntFlagView: newMchntFlagView,//活动期间新增商户
        afterFlagView: afterFlagView,//手续费优惠规则
        beforeFlagView: beforeFlagView,//达标前的交易通过返现营销
        postponeFlagView: postponeFlagView,//新增商户营销结束日期在营销活动结束日期之后
        stockMchnt: stockMchnt,//达标条件
        depositMonNum: mcInfoObj.depositMonNum,//月均存款平均月数
        statPeriod: mcInfoObj.statPeriod,//统计周期
        effectiveLimitTranNum: mcInfoObj.effectiveLimit,// 有效交易为：交易金额 ≥ 交易笔数
        effectiveLimitTranMoney: mcInfoObj.effectiveLimit,//有效交易为：交易金额 ≥交易笔数
        discoutPeriodTranNum: ruleInfoList[0].discountPeriod,//有效周期
        discoutPeriodTranMoney: ruleInfoList[0].discountPeriod,//有效周期
        discoutPeriodFeeMoney: ruleInfoList[0].discountPeriod,//有效周期
        newMchntPeriod: mcInfoObj.newMchntPeriod,//新增商户免手续费周期
        newMchntAmountLimit: mcInfoObj.newMchntAmountLimit,//每月优惠交易最大金额
        quantityLimit: quantityLimit,//单个存量商户优惠交易笔数上限
        amountLimit: amountLimit,//单个存量商户优惠交易金额上限
        feeLimit: feeLimit,//单个存量商户手续费优惠额上限
        flag: flag,//详细页面标识
        mcType: mcInfoObj.mcType//营销活动类型
        //end优惠劵
      }
    },
    view(record) {
      if (["00", "01", "02", "03", "10", "11"].includes(record.mcType)) { // 银行对商户手续费优惠活动详情

      } else if (record.mcType == "20") { // 银行对客营销活动活动详情
        // this.component = MarketActiManageForCustOperation;
        // this.$nextTick(()=>{
        //   this.$refs.detail.show({}, 'view')
        // })
        this.component = CommissionMarketManagerOperation
        this.$nextTick(async () => {
          const hide = this.$message.loading("加载中...", 0);
          try {
            const res = await this.$get('/admin/market/commissionManager/view?flag=chkView&mcNo=' + record.mcNo)
            if (res.data.datailData) {
              this.$refs.detail.show(this.resolveBeanInfo2(res.data), 'view')
            }
          } catch (e) {
            console.error(e)
          }
          hide()
        })
      } else if (record.mcType == "30") { // 代理商分润营销活动详情
      } else if (record.mcType == "40") { // 收银员返现营销活动详情
        this.component = CashierManagerOperation
        this.$nextTick(async () => {
          const hide = this.$message.loading("加载中...", 0);
          try {
            const res = await this.$get('/admin/market/cashierManager/toDetails?mcNo=' + record.mcNo)
            if (res.data.datailData) {
              this.$refs.detail.show(this.resolveBeanInfo(res.data), 'view')
            }
          } catch (e) {
            console.error(e)
          }
          hide()
        })
      } else {
        this.$message.error('该数据活动类型有误，请联系管理员')
      }
    },
    async check(record) {
      if (record.attendFlag === '1') {
        this.$message.error("上级创建的活动不能审核")
        return
      }
      if (record.auditStatus !== '01' && record.auditStatus !== '11' && record.auditStatus !== '21' && record.auditStatus !== '31' && record.auditStatus !== '41') {
        this.$message.error("只可审核审批流程中的营销活动")
        return
      }
      // 根据活动类型，跳转不同审批页面
      if (["00", "01", "02", "03", "10", "11"].includes(record.mcType)) {

      } else if (record.mcType == "20") { // 银行对客营销活动活动详情
        // console.log('银行对客营销活动活动详情')
        // this.component = MarketActiManageForCustOperation;
        // this.$nextTick(() => {
        //   this.$refs.detail.show({}, 'examine')
        // });
        this.component = CommissionMarketManagerOperation
        this.$nextTick(async () => {
          const hide = this.$message.loading("加载中...", 0);
          try {
            const res = await this.$get('/admin/market/commissionManager/view?flag=check&mcNo=' + record.mcNo)
            if (res.data.datailData) {
              this.$refs.detail.show(this.resolveBeanInfo2(res.data), 'examine')
            }
          } catch (e) {
            console.error(e)
          }
          hide()
        })
      } else if (record.mcType == "30") { // 代理商分润营销活动详情
      } else if (record.mcType == "40") { // 收银员返现营销活动详情
        this.component = CashierManagerOperation
        this.$nextTick(async () => {
          const hide = this.$message.loading("加载中...", 0);
          try {
            const res = await this.$get('/admin/market/cashierManager/toCheck', {
              auditStatus: record.auditStatus,
              mcNo: record.mcNo,
            })
            if (res.data.datailData) {
              this.$refs.detail.show(this.resolveBeanInfo(res.data), 'examine')
            }
          } catch (e) {
            console.error(e)
          }
          hide()
        })
      } else {
        this.$message.error('该数据活动类型有误，请联系管理员')
      }
    }
  },
  mounted() {
    this.search()
  }

}
</script>

<style scoped>
.operation {
  margin-bottom: 10px;
}

.page {
  width: 100%;
}

/deep/ .scrollable .ant-table td {
  white-space: nowrap;
}
</style>
